package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.converter.UserPrivilegeConverter;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.UserVocAISituationDTO;
import com.cskaoyan.wordmemorize.dto.admin.UserVocAISituationOptionDTO;
import com.cskaoyan.wordmemorize.dto.app.*;
import com.cskaoyan.wordmemorize.dao.entity.*;
import com.cskaoyan.wordmemorize.dao.mapper.*;
import com.cskaoyan.wordmemorize.request.AIReviewReadCommand;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.UserFavoriteCommand;
import com.cskaoyan.wordmemorize.request.UserVocExampleSentenceCommand;
import com.cskaoyan.wordmemorize.service.UserPrivilegeService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户特权服务实现类
 */
@Service
@Slf4j
public class UserPrivilegeServiceImpl implements UserPrivilegeService {

    // ChatClient
    private final ChatClient chatClient;
    @Autowired
    private UserNotRememberMapper userNotRememberMapper;
    @Autowired
    private UserVocExampleSentenceMapper userVocExampleSentenceMapper;
    @Autowired
    private UserVocAISituationMapper userVocAISituationMapper;
    @Autowired
    private UserVocAISituationOptionMapper userVocAISituationOptionMapper;
    @Autowired
    private UserPrivilegeHistoryMapper userPrivilegeHistoryMapper;
    @Autowired
    private UserVocBoundStatisticsMapper userVocBoundStatisticsMapper;
    @Autowired
    private UserVocBoundLogMapper userVocBoundLogMapper;
    @Autowired
    private UserFavoriteMapper userFavoriteMapper;
    @Autowired
    private VocMapper vocMapper;
    @Autowired
    private VocChapBookMapper vocChapBookMapper;


    @Autowired
    private VocBookMapper vocBookMapper;
    @Autowired
    private UserVocRevMapper userVocRevMapper;
    @Autowired
    private UserPrivilegeConverter userPrivilegeConverter;
    @Autowired
    private VocMeaningMapper vocMeaningMapper;

    public UserPrivilegeServiceImpl(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    /**
     * APP端获取词书进度
     *
     * @param userId 用户ID
     * @param bookId 词书ID
     * @return UserVocBookStatisticsDTO 词书进度数据
     */
    @Override
    public UserVocBookStatisticsDTO getSelectedBookStatistics(Long userId, Long bookId) {
        // 实现获取词书进度的逻辑
        //        词书进度涉及到的表有: user_voc_rev, voc_chap_book, voc_book
        // 1 获取该书籍的单词总数
        VocBookDO vocBookDO = vocBookMapper.selectById(bookId);
        Integer vocCount = vocBookDO.getVocCount();
        // 2 查出这些单词有多少属于该书籍
        List<VocChapBookDO> vocChapBookDOList = vocChapBookMapper.selectList(new QueryWrapper<VocChapBookDO>().eq("book_id", bookId));
        List<Long> collect = vocChapBookDOList.stream().map(VocChapBookDO::getVocId).collect(Collectors.toList());

        //        熟悉的单词数量: 单词的复习间隔>= 365的单词
        LambdaQueryWrapper<UserVocRevDO> userVocRevFamiliarityQueryWrapper = new LambdaQueryWrapper<>();
        userVocRevFamiliarityQueryWrapper.eq(UserVocRevDO::getUserId, userId)
                .gtSql(UserVocRevDO::getReviewInterval, "365")
                .in(UserVocRevDO::getVocId, collect);

        Long familiarityCount = userVocRevMapper.selectCount(userVocRevFamiliarityQueryWrapper);
        //        不熟悉的单词指: 还处于学习状态的单词(单词复习的时间间隔=1)

        LambdaQueryWrapper<UserVocRevDO> userVocRevUnFamiliarityQueryWrapper = new LambdaQueryWrapper<>();
        userVocRevUnFamiliarityQueryWrapper.eq(UserVocRevDO::getUserId, userId)
                .eq(UserVocRevDO::getReviewInterval, 1)
                .in(UserVocRevDO::getVocId, collect);

        Long unFamiliarCount = userVocRevMapper.selectCount(userVocRevUnFamiliarityQueryWrapper);
        //        一般的单词:  已处于复习状态，且复习时间间隔 < 365的单词

        LambdaQueryWrapper<UserVocRevDO> userVocRevNormalQueryWrapper = new LambdaQueryWrapper<>();
        userVocRevNormalQueryWrapper.eq(UserVocRevDO::getUserId, userId)
                .gt(UserVocRevDO::getReviewInterval, 1)
                .lt(UserVocRevDO::getReviewInterval, 365)
                .in(UserVocRevDO::getVocId, collect);

        Long generalCount = userVocRevMapper.selectCount(userVocRevNormalQueryWrapper);
        //        未开始单词数量。

        LambdaQueryWrapper<UserVocRevDO> userVocRevNotStartQueryWrapper = new LambdaQueryWrapper<>();
        userVocRevNormalQueryWrapper.eq(UserVocRevDO::getUserId, userId)
                .eq(UserVocRevDO::getTotalReview, 0)
                .in(UserVocRevDO::getVocId, collect);

        Long notStartCount = userVocRevMapper.selectCount(userVocRevNotStartQueryWrapper);

        // 未选择单词数量
        Integer unSelectedCount = Math.toIntExact(vocCount - notStartCount - familiarityCount - unFamiliarCount - generalCount);
        // 封装返回对象
        UserVocBookStatisticsDTO userVocBookStatisticsDTO = new UserVocBookStatisticsDTO();
        userVocBookStatisticsDTO.setNotStarted(notStartCount.intValue());
        userVocBookStatisticsDTO.setTotal(vocCount);
        userVocBookStatisticsDTO.setFamiliar(familiarityCount.intValue());
        userVocBookStatisticsDTO.setUnFamiliar(unFamiliarCount.intValue());
        userVocBookStatisticsDTO.setUnSelected(unSelectedCount);
        userVocBookStatisticsDTO.setGeneral(generalCount.intValue());

        return userVocBookStatisticsDTO;
    }

    /**
     * APP端批量添加收藏单词
     *
     * @param userFavoriteCommandList 用户收藏单词请求体列表
     * @param userId                  用户ID
     */

    @Override
    public void addFavoriteBulk(List<UserFavoriteCommand> userFavoriteCommandList, Long userId) {
        // 实现批量添加收藏单词的逻辑  接收到的只有单词ID
        //  不考虑前端发送重复数据
        List<UserFavoriteDO> userFavoriteDOS = userPrivilegeConverter.userFavoriteDOs2DTOs(userFavoriteCommandList);

        userFavoriteDOS.forEach(userFavoriteDO -> {
            userFavoriteDO.setUserId(userId);
            // 单词收藏涉及的表有: user_favorite，voc_meaning(因为在收藏列表中还会显示单词释义)，
            // user_voc_rev(还可以显示该单词是否已选择复习)
            Long l = userVocRevMapper.selectCount(new LambdaQueryWrapper<UserVocRevDO>()
                    .eq(UserVocRevDO::getVocId, userFavoriteDO.getVocId())
                    .eq(UserVocRevDO::getUserId, userId)
            );
            if (l > 0) {
                // 有记录说明已经被选择了
                userFavoriteDO.setSelected(1);
            }

            VocDO vocDO = vocMapper.selectById(userFavoriteDO.getVocId());
            userFavoriteDO.setVocContent(vocDO.getContent());

            // 获取单词收藏对象  判断是否存在
            UserFavoriteDO exists = vocMapper.getUserFavoriteDO(userFavoriteDO);


            if (exists == null) {
                userFavoriteMapper.insert(userFavoriteDO);
            } else {
                userFavoriteDO.setId(exists.getId());
                userFavoriteDO.setSelected(0);
                vocMapper.updateUserFavoriteDO(userFavoriteDO);
            }
        });
    }

    /**
     * APP端单个添加收藏单词
     *
     * @param userFavoriteCommand 用户收藏单词请求体
     * @param userId              用户ID
     */

    @Override
    public void addFavorite(UserFavoriteCommand userFavoriteCommand, Long userId) {
        // 单词收藏涉及的表有: user_favorite，voc_meaning(因为在收藏列表中还会显示单词释义)，
        // user_voc_rev(还可以显示该单词是否已选择复习)

        UserFavoriteDO userFavoriteDO = userPrivilegeConverter.userFavoriteCommand2DO(userFavoriteCommand);

        userFavoriteDO.setUserId(userId);
        // 单词收藏涉及的表有: user_favorite，voc_meaning(因为在收藏列表中还会显示单词释义)，
        // user_voc_rev(还可以显示该单词是否已选择复习)
        Long l = userVocRevMapper.selectCount(new LambdaQueryWrapper<UserVocRevDO>()
                .eq(UserVocRevDO::getVocId, userFavoriteDO.getVocId())
                .eq(UserVocRevDO::getUserId, userId)
        );
        if (l > 0) {
            // 有记录说明已经被选择了
            userFavoriteDO.setSelected(1);
        }

        VocDO vocDO = vocMapper.selectById(userFavoriteDO.getVocId());
        userFavoriteDO.setVocContent(vocDO.getContent());


        // 获取单词收藏对象  判断是否存在
        UserFavoriteDO exists = vocMapper.getUserFavoriteDO(userFavoriteDO);


        if (exists == null) {
            userFavoriteMapper.insert(userFavoriteDO);
        } else {
            userFavoriteDO.setId(exists.getId());
            userFavoriteDO.setSelected(0);
            vocMapper.updateUserFavoriteDO(userFavoriteDO);
        }

    }

    /**
     * APP端取消收藏单词
     *
     * @param ids    要取消收藏的单词ID列表
     * @param userId 用户ID
     */

    @Override
    public void cancelFavorite(List<Long> ids, Long userId) {
        // 实现取消收藏单词的逻辑

        userFavoriteMapper.delete(new QueryWrapper<UserFavoriteDO>()
                .eq("user_id", userId)
                .eq("is_deleted", 0)
                .in("voc_id", ids));


    }

    /**
     * APP端获取单词收藏列表
     *
     * @param pageRequest 分页查询请求体
     * @param userId      用户ID
     * @return UserFavoriteDTO 用户单词收藏列表 分页查询结果
     */
    @Override
    public PageDTO<UserFavoriteDTO> getUserFavoriteList(PageRequest pageRequest, Long userId) {
        LambdaQueryWrapper<UserFavoriteDO> userFavoriteDOQueryWrapper = new LambdaQueryWrapper<>();
        userFavoriteDOQueryWrapper.eq(UserFavoriteDO::getUserId, userId);
        Page<UserFavoriteDO> userFavoriteDOPage = new Page<>();
        if (pageRequest.getCount() != null && pageRequest.getPageNum() != null
                && pageRequest.getCount() != 0 && pageRequest.getPageNum() != 0) {
            userFavoriteDOPage.setCurrent(pageRequest.getPageNum());
            userFavoriteDOPage.setSize(pageRequest.getCount());
        }
        // 判断keyword
        userFavoriteDOQueryWrapper.like(pageRequest.getKeyword() != null, UserFavoriteDO::getVocContent, pageRequest.getKeyword());

        Page<UserFavoriteDO> PageUserFavoriteDO = userFavoriteMapper.selectPage(userFavoriteDOPage, userFavoriteDOQueryWrapper);

        PageUserFavoriteDO.getRecords().forEach(userFavoriteDO -> {
            // 去voc_meaning表获取单词释义
            List<VocMeaningDO> vocMeaningDOS = vocMeaningMapper.selectList(new LambdaQueryWrapper<VocMeaningDO>()
                    .eq(VocMeaningDO::getVocId, userFavoriteDO.getVocId()));
            userFavoriteDO.setInterpretations(vocMeaningDOS);

        });

        // 实现获取单词收藏列表的逻辑
        return userPrivilegeConverter.userFavoriteDOPage2PageDTO(PageUserFavoriteDO.getRecords(), PageUserFavoriteDO.getTotal());
    }

    /**
     * APP端添加用户自建例句
     *
     * @param command 用户自建例句请求体
     * @param userId  用户ID
     */
    // APP端添加用户自建例句
    @Override
    public void addUserVocSentence(UserVocExampleSentenceCommand command, Long userId) {
        UserVocExampleSentenceDO userVocExampleSentenceDO = new UserVocExampleSentenceDO();
        userVocExampleSentenceDO.setUserId(userId);
        userVocExampleSentenceDO.setVocId(Long.valueOf(command.getVocId()));
        userVocExampleSentenceDO.setSentence(command.getSentence());
        userVocExampleSentenceDO.setMeaning(command.getMeaning());
        userVocExampleSentenceDO.setVocContent(command.getVocContent());


        userVocExampleSentenceMapper.insert(userVocExampleSentenceDO);
    }

    /**
     * APP端获取用户自建例句
     *
     * @param pageRequest 分页查询请求体
     * @param userId      用户ID
     * @return DisplayUserVocSentenceDTO 用户自建例句展示数据 分页查询结果
     */
    @Override
    public PageDTO<DisplayUserVocSentenceDTO> getUserVocSentence(PageRequest pageRequest, Long userId) {
        // 实现获取用户自建例句的逻辑

        List<DisplayUserVocSentenceDTO> displayUserVocSentenceDTO = vocMapper.getUserVocExampleSentences(pageRequest, userId);

        PageDTO<DisplayUserVocSentenceDTO> userVocExampleSentenceDOPage = new PageDTO<>();
        userVocExampleSentenceDOPage.setPageList(displayUserVocSentenceDTO);


        return userVocExampleSentenceDOPage;

//        return null;

    }

    /**
     * APP端更新用户自建例句
     *
     * @param command 用户自建例句请求体
     * @param userId  用户ID
     */
    // TODO
    // APP端更新用户自建例句
    @Override
    public void updateUserVocSentence(UserVocExampleSentenceCommand command, Long userId) {
        UserVocExampleSentenceDO userVocExampleSentenceDO = userVocExampleSentenceMapper.selectById(command.getId());
        if (userVocExampleSentenceDO != null && userVocExampleSentenceDO.getUserId().equals(userId)) {
            userVocExampleSentenceDO.setSentence(command.getSentence());
            userVocExampleSentenceDO.setMeaning(command.getMeaning());


            userVocExampleSentenceMapper.updateById(userVocExampleSentenceDO);
        }
    }

    /**
     * APP端删除用户自建例句
     *
     * @param id 自建例句ID
     */
    @Override
    public void deleteUserVocSentence(Long id) {
        userVocExampleSentenceMapper.deleteById(id);
    }

    /**
     * APP端标记单词为不背
     *
     * @param vocId  单词ID
     * @param userId 用户ID
     */

    @Override
    @Transactional
    public void notRemember(Long vocId, Long userId) {
        // 检查是否已经标记为不背
        LambdaQueryWrapper<UserNotRememberDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserNotRememberDO::getUserId, userId).eq(UserNotRememberDO::getVocId, vocId);

        UserNotRememberDO existingRecord = userNotRememberMapper.selectOne(queryWrapper);

        if (existingRecord == null) {
            // 如果不存在，则创建新记录
            UserNotRememberDO userNotRememberDO = new UserNotRememberDO();
            userNotRememberDO.setUserId(userId);
            userNotRememberDO.setVocId(vocId);
            // BaseDO类中没有createTime和updateTime字段，所以不需要设置
            userNotRememberMapper.insert(userNotRememberDO);
        }
    }

    /**
     * APP端取消标记单词为不背
     *
     * @param vocId  单词ID
     * @param userId 用户ID
     */
    // TODO
    @Override
    @Transactional
    public void cancelNotRemember(Long vocId, Long userId) {
        // 删除"不背"标记
        LambdaQueryWrapper<UserNotRememberDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserNotRememberDO::getUserId, userId).eq(UserNotRememberDO::getVocId, vocId);

        userNotRememberMapper.delete(queryWrapper);
    }

    // 已删除接口 无需实现
//    @Override
//    public List<UserReviewFillWordDTO> getUserReviewFillWordTopics(List<Long> vocIds) {
//        // 实现获取选词填空题列表的逻辑
//        return null;
//    }
//
//    @Override
//    public List<UserReviewSingleChoiceDTO> getVocSingleChoiceTopic(List<Long> vocIds) {
//        // 实现获取单选题目列表的逻辑
//        return null;
//    }

    /**
     * APP端获取AI阅读模式以及选项
     *
     * @return UserVocAISituationDTO AI阅读模式以及选项数据
     */
    @Override
    public List<UserVocAISituationDTO> getAIReviewReadOptions() {
        // 查询所有可用的 AI 阅读场景（状态为1的场景）
        List<UserVocAISituationDO> situationList = userVocAISituationMapper.selectList(
                new LambdaQueryWrapper<UserVocAISituationDO>()
                        .eq(UserVocAISituationDO::getStatus, 1)
        );

        if (CollectionUtils.isEmpty(situationList)) {
            return Collections.emptyList();
        }

        // 转换为DTO列表
        List<UserVocAISituationDTO> situationDTOList = new ArrayList<>();
        for (UserVocAISituationDO situationDO : situationList) {
            UserVocAISituationDTO situationDTO = new UserVocAISituationDTO();
            BeanUtils.copyProperties(situationDO, situationDTO);

            // 查询每个场景对应的选项
            List<UserVocAISituationOptionDO> optionList = userVocAISituationOptionMapper.selectList(
                    new LambdaQueryWrapper<UserVocAISituationOptionDO>()
                            .eq(UserVocAISituationOptionDO::getSituationId, situationDO.getId())
            );

            // 转换选项为DTO列表
            if (!CollectionUtils.isEmpty(optionList)) {
                List<UserVocAISituationOptionDTO> optionDTOList = new ArrayList<>();
                for (UserVocAISituationOptionDO optionDO : optionList) {
                    UserVocAISituationOptionDTO optionDTO = new UserVocAISituationOptionDTO();
                    BeanUtils.copyProperties(optionDO, optionDTO);
                    optionDTOList.add(optionDTO);
                }
                situationDTO.setOptions(optionDTOList);
            }

            situationDTOList.add(situationDTO);
        }

        return situationDTOList;
    }

    /**
     * APP端获取用户剩余免费AI阅读次数
     *
     * @param userId 用户ID
     * @return Integer 用户剩余免费AI阅读次数
     */
    @Override
    public Integer getUserVocAIReadRemainFreeCount(Long userId) {
        // 定义AI阅读功能的特权代码
        final String AI_READ_PRIVILEGE_CODE = "review:ai:read";
        // 定义免费使用次数上限
        final int FREE_AI_READ_COUNT = 10;

        // 查询用户已使用的AI阅读次数
        UserPrivilegeUseStatisticsDO statisticsDO = userPrivilegeHistoryMapper.selectOne(
                new LambdaQueryWrapper<UserPrivilegeUseStatisticsDO>()
                        .eq(UserPrivilegeUseStatisticsDO::getUserId, userId)
                        .eq(UserPrivilegeUseStatisticsDO::getPrivilegeCode, AI_READ_PRIVILEGE_CODE)
        );

        // 如果没有使用记录，则返回免费次数上限
        if (statisticsDO == null) {
            return FREE_AI_READ_COUNT;
        }

        // 计算剩余免费次数
        int usedCount = statisticsDO.getUseCount() != null ? statisticsDO.getUseCount() : 0;
        int remainCount = Math.max(0, FREE_AI_READ_COUNT - usedCount);

        return remainCount;
    }

    /**
     * APP端获取AI阅读结果
     *
     * @param command AI阅读命令
     * @param userId  用户ID
     * @return AIReviewReadDTO AI阅读结果列表
     */
    @Override
    public List<AIReviewReadDTO> getAIReviewReadContent(AIReviewReadCommand command, Long userId) {
        // 验证参数
        if (command == null || CollectionUtils.isEmpty(command.getVocList()) ||
                StringUtils.isEmpty(command.getSituationName()) || StringUtils.isEmpty(command.getOptionName())) {
            throw new BusinessException("参数不能为空", 400);
        }

        // 检查用户是否有剩余免费次数
        Integer remainFreeCount = getUserVocAIReadRemainFreeCount(userId);

        // 如果免费次数用完，检查并扣除用户单词上限
        if (remainFreeCount <= 0) {
            // 每次使用AI阅读需要扣除的单词上限数量
            final int AI_READ_COST = 10;

            // 查询用户单词上限统计信息
            UserVocBoundStatisticsDO userVocBoundStatistics = userVocBoundStatisticsMapper.selectOne(
                    new LambdaQueryWrapper<UserVocBoundStatisticsDO>()
                            .eq(UserVocBoundStatisticsDO::getUserId, userId)
            );

            // 如果用户没有单词上限记录或可用上限不足
            if (userVocBoundStatistics == null || userVocBoundStatistics.getAvailable() < AI_READ_COST) {
                throw new BusinessException("您的免费AI阅读次数已用完，且可用单词上限不足", 403);
            }

            // 扣除用户单词上限
            userVocBoundStatistics.setAvailable(userVocBoundStatistics.getAvailable() - AI_READ_COST);
            userVocBoundStatisticsMapper.updateById(userVocBoundStatistics);

            // 记录单词上限变更日志
            UserVocBoundLogDO userVocBoundLog = new UserVocBoundLogDO();
            userVocBoundLog.setUserId(userId);
            userVocBoundLog.setCount(-AI_READ_COST); // 负数表示减少
            userVocBoundLog.setType(3);
            userVocBoundLog.setDescription("使用AI阅读功能消耗" + AI_READ_COST + "个单词上限");
            userVocBoundLogMapper.insert(userVocBoundLog);
        }

        try {
            // 获取提示词模板
            Resource systemMessageResource = new ClassPathResource("prompt/ai-read-system-message.st");
            Resource userMessageResource = new ClassPathResource("prompt/ai-read-user-message.st");

            String systemMessageTemplate = StreamUtils.copyToString(systemMessageResource.getInputStream(), StandardCharsets.UTF_8);
            String userMessageTemplate = StreamUtils.copyToString(userMessageResource.getInputStream(), StandardCharsets.UTF_8);

            // 替换用户消息模板中的占位符
            String userMessage = userMessageTemplate
                    .replace("{situation}", command.getSituationName())
                    .replace("{option}", command.getOptionName())
                    .replace("{words}", String.join(", ", command.getVocList()))
                    .replace("{type}", command.getSituationName() + "-" + command.getOptionName());

            // 创建 Prompt
            Prompt prompt = new Prompt(
                    new SystemMessage(systemMessageTemplate),
                    new UserMessage(userMessage)
            );

            // 调用 OpenAI 生成内容
            ChatResponse response =
                    chatClient
                            // 设置prompt
                            .prompt(prompt)
                            // 发起请求
                            .call()
                            // 获取结果
                            .chatResponse();
            String content = null;
            if (response != null) {
                content = response.getResults().toString();
            } else {
                throw new BusinessException("获取AI阅读内容失败", 500);
            }

            // 更新用户使用统计
            updateUserAIReadUsageCount(userId);

            // 解析返回的内容
            return parseAIReadContent(content);

        } catch (Exception e) {
            log.error("获取AI阅读内容失败", e);
            throw new BusinessException("获取AI阅读内容失败: " + e.getMessage(), 500);
        }
    }

    /**
     * 更新用户AI阅读使用次数
     *
     * @param userId 用户ID
     */
    private void updateUserAIReadUsageCount(Long userId) {
        final String AI_READ_PRIVILEGE_CODE = "review:ai:read";

        // 查询用户使用记录
        UserPrivilegeUseStatisticsDO statisticsDO = userPrivilegeHistoryMapper.selectOne(
                new LambdaQueryWrapper<UserPrivilegeUseStatisticsDO>()
                        .eq(UserPrivilegeUseStatisticsDO::getUserId, userId)
                        .eq(UserPrivilegeUseStatisticsDO::getPrivilegeCode, AI_READ_PRIVILEGE_CODE)
        );

        if (statisticsDO == null) {
            // 创建新记录
            statisticsDO = new UserPrivilegeUseStatisticsDO();
            statisticsDO.setUserId(userId);
            statisticsDO.setPrivilegeCode(AI_READ_PRIVILEGE_CODE);
            statisticsDO.setUseCount(1);
            userPrivilegeHistoryMapper.insert(statisticsDO);
        } else {
            // 更新使用次数
            statisticsDO.setUseCount(statisticsDO.getUseCount() != null ? statisticsDO.getUseCount() + 1 : 1);
            userPrivilegeHistoryMapper.updateById(statisticsDO);
        }
    }


    /**
     * 解析AI返回的内容，转换为AIReviewReadDTO列表
     *
     * @param content AI返回的内容
     * @return AIReviewReadDTO列表
     */
    private List<AIReviewReadDTO> parseAIReadContent(String content) {
        List<AIReviewReadDTO> result = new ArrayList<>();

        // 按段落分割内容
        String[] paragraphs = content.split("\\n\\n");

        boolean isEnglish = true; // 标记当前段落是英文还是中文
        AIReviewReadDTO currentDTO = null;

        for (String paragraph : paragraphs) {
            if (StringUtils.isEmpty(paragraph.trim())) {
                continue;
            }

            // 如果是英文段落，创建新的DTO并设置英文内容
            if (isEnglish) {
                currentDTO = new AIReviewReadDTO();
                currentDTO.setSegment(paragraph.trim());
                isEnglish = false;
            } else {
                // 如果是中文段落，设置中文翻译并添加到结果列表
                if (currentDTO != null) {
                    currentDTO.setSegmentTranslation(paragraph.trim());
                    result.add(currentDTO);
                }
                isEnglish = true;
            }
        }

        return result;
    }
}
